from application import jsonrpc
import re,random,json
from status import APIStatus as status
from message import ErrorMessage as message
from ronglian_sms_sdk import SmsSDK
from flask import current_app
from application import redis
@jsonrpc.method(name="Home.sms")
def sms(mobile):
    """发送短信验证码"""
    # 验证手机
    if not re.match("^1[3-9]\d{9}$",mobile):
        return {"errno": status.CODE_VALIDATE_ERROR, "errmsg": message.mobile_format_error}

    # 短信发送冷却时间
    ret = redis.get("int_%s" % mobile)
    if ret is not None:
        return {"errno": status.CODE_INTERVAL_TIME, "errmsg": message.sms_interval_time}

    # 生成验证码
    sms_code = "%06d" % random.randint(0,999999)
    try:
        # 异步发送短信
        from mycelery.sms.tasks import send_sms
        send_sms.delay(mobile=mobile, sms_code=sms_code)
        # 返回结果
        return {"errno":status.CODE_OK, "errmsg": message.sms_is_send}
    except Exception as e:
        return {"errno": status.CODE_SMS_ERROR, "errmsg": message.sms_send_error}